﻿using Identity_JWT_WebAPI.Dao.Model;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;

namespace Identity_JWT_WebAPI.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class IdentityController : ControllerBase
    {
        private UserManager<User> userManager;
        private RoleManager<Role> roleManager;

        public IdentityController(UserManager<User> userManager, RoleManager<Role> roleManager)
        {
            this.userManager = userManager;
            this.roleManager = roleManager;
            this.userManager.UserValidators.Clear();  //把验证的机制去掉
            this.roleManager.RoleValidators.Clear();    //把验证的机制去掉
        }

        /// <summary>
        /// 添加角色信息
        /// </summary>
        /// <param name="roleName"></param>
        /// <returns></returns>
        [HttpPost]
        //[Authorize(Roles = "Admin,admin")]
        public async Task<ActionResult<string>> AddRole(string roleName)
        {
            Role role = await roleManager.FindByNameAsync(roleName);
            if (role is null)
            {
                role = new Role { Name = roleName };
            }
            IdentityResult result = await roleManager.CreateAsync(role);
            if (!result.Succeeded) return BadRequest("创建角色 失败");
            return "角色创建成功";
        }

        /// <summary>
        /// 注册用户信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ActionResult<string>> RegistUser(string email, string pwd)
        {
            User user = await userManager.FindByEmailAsync(email);
            if (user is null)
            {
                user = new User { Email = email,EmailConfirmed=true };
                IdentityResult result = await userManager.CreateAsync(user, pwd);
                if (!result.Succeeded) return BadRequest("创建用户信息 失败");
            }
            return "用户创建成功";
        }

        /// <summary>
        /// 为用户添加角色
        /// </summary>
        /// <param name="email"></param>
        /// <param name="roleName"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ActionResult<string>> AddRoleByUser(string email, string roleName)
        {
            User myuser = await userManager.FindByEmailAsync(email);
            if (myuser is null) return BadRequest("用户信息 不存在");
            Role myrole = await roleManager.FindByNameAsync(roleName);
            if (myrole is null) return BadRequest("角色信息 不存在");
            IdentityResult result= await userManager.AddToRoleAsync(myuser,roleName);
            if (!result.Succeeded) return BadRequest("添加角色失败");
            return "Ok";
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="email"></param>
        /// <param name="pwd"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ActionResult<string>> Login(string email, string pwd) 
        {
            User user = await userManager.FindByEmailAsync(email);
            if (user is null) return BadRequest("用户信息 不存在");
            if (await userManager.IsLockedOutAsync(user)) return BadRequest("用户被锁定，锁定时间：" + user.LockoutEnd);
            if (await userManager.CheckPasswordAsync(user, pwd))
            {
                await userManager.ResetAccessFailedCountAsync(user); //重置登录失败
                return Ok("成功");
            }
            else await userManager.AccessFailedAsync(user); //记录登录失败
            return BadRequest("登录失败");


        }


        /// <summary>
        /// 重置密码，发送Token
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ActionResult<string>> ResetPWDBySendToken(string userName)
        {
            var user = await userManager.FindByNameAsync(userName);
            if (user is null) return BadRequest("用户名不存在");
            string token = await userManager.GeneratePasswordResetTokenAsync(user);
            return Ok("Token:" + token);
        }
        /// <summary>
        /// 重置密码
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="token"></param>
        /// <param name="pwd"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ActionResult<string>> ResetPassword(string userName, string token, string pwd)
        {
            var user = await userManager.FindByNameAsync(userName);
            if (user is null) return BadRequest("用户名不存在");
            var result = await userManager.ResetPasswordAsync(user, token, pwd);
            if (result.Succeeded) return Ok("更新密码成功");
            return BadRequest("更新密码失败");
        }

    }
}
